package fun.sboy.headacheMemo.controller;

import fun.sboy.headacheMemo.entry.User;
import fun.sboy.headacheMemo.service.UserService;
import fun.sboy.headacheMemo.util.ResultUtils;
import fun.sboy.headacheMemo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
/**
 * 登录、注册
 */
public class LoginController {

    public static final String REDIS_LOGIN_PREFIX = "LoginUserToken";
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResultUtils login(@RequestBody User user) {
        User loginUser = userService.login(user);
        if (loginUser == null) {
            return ResultUtils.fail("登录失败，账号或密码错误！");
        }
        String token = getToken(loginUser.getId());
        return ResultUtils.success("登录成功", token);
    }

    @PostMapping("/register")
    public ResultUtils register(User user) {
        userService.register(user);
        //返回token
        return ResultUtils.success(getToken(user.getId()));
    }


    private String getToken(String uid) {
        String token = TokenUtil.generatorToken(uid, null);
        redisTemplate.opsForValue().set(REDIS_LOGIN_PREFIX + uid, token, 24, TimeUnit.HOURS);
        return token;
    }
}